package com.x.client.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.x.client.model.User;
import com.x.client.payload.ClientSmsCodeMsg;
import com.x.client.rpc.UserRpcService;
import com.x.client.util.ClientConstantTopic;
import com.x.client.util.Constant;
import com.x.crm.model.Customer;
import com.x.crm.model.CustomerShop;
import com.x.crm.model.Intention;
import com.x.crm.model.IntentionModel;
import com.x.crm.rpc.CustomerRpcService;
import com.x.crm.rpc.CustomerShopRpcService;
import com.x.crm.rpc.IntentionModelRpcService;
import com.x.crm.rpc.IntentionRpcService;
import com.x.erp.model.Car;
import com.x.erp.rpc.CarRpcService;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import com.x.framework.redis.XRedisTemplate;
import com.x.rocketmq.RocketMqProducer;
import com.x.security.model.SecurityAccount;
import com.x.security.util.JWT;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;


@RestController
@RequestMapping(value = "/clientUser")
public class UserController extends BaseController{

	@Autowired
	private RocketMqProducer rocketMqProducer;

	@Autowired
	private XRedisTemplate redis;

	@Reference
	private UserRpcService userRpcService;// 车辆图片服务

	@Reference
	private CarRpcService carRpcService;// 用户

	@Reference
	private CustomerRpcService customerRpcService;// 用户

	@Reference
	private CustomerShopRpcService customerShopRpcService;// 用户

	@Reference
	private IntentionRpcService intentionRpcService;// 用户

	@Reference
	private IntentionModelRpcService intentionModelRpcService;// 用户




	@RequestMapping(value = "/login", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel login(@Validated User user, BindingResult bindingResult, String validateCode, HttpServletResponse response, HttpServletRequest request){
		if (bindingResult.hasErrors()){
			List<ObjectError> errors = bindingResult.getAllErrors();
			return new ResultModel(ResultCode.RESULT_FAIL, errors.get(0).getDefaultMessage());
		}
		if (StringUtils.isEmpty(validateCode)){
			return new ResultModel(ResultCode.RESULT_FAIL, "验证码不能为空！");
		}
		String userMobile = user.getUserMobile();
		if(!userMobile.equals("18811132880") || !validateCode.equals("061542")){
			ClientSmsCodeMsg clientSmsCodeMsg = JSON.parseObject(redis.get("clientLoginSmsValidCode_" + userMobile), ClientSmsCodeMsg.class);
			if (clientSmsCodeMsg == null || !clientSmsCodeMsg.getValidateCode().equals(validateCode)) {
				return new ResultModel(ResultCode.RESULT_FAIL, "验证码不正确");
			}
		}
		User userInfo = userRpcService.selectUserInfo(new User(user.getUserMobile()));
		if (userInfo == null){
			Random r = new Random();
			String code = String.format("%06d", r.nextInt(1000000));
			String nativeToken = userMobile + code;
			user.setUserToken(nativeToken);
			String source = request.getHeader("source");
			if(StringUtils.isEmpty (source)){
				return new ResultModel(ResultCode.RESULT_FAIL, "用户来源不能为空");
			}
			user.setUserSource(source);
			Date cDate = this.getDate(0);
			user.setUserCreateTime(cDate);
			user.setUserUpdateTime(cDate);
			userInfo = userRpcService.insertUser(user);
		}
		if(StringUtils.isNotEmpty(user.getWxOpenId()) && StringUtils.isEmpty(userInfo.getWxOpenId())){
			userInfo.setWxOpenId(user.getWxOpenId());
			userInfo.setUserNickname(user.getUserNickname());
			userInfo.setUserHead(user.getUserHead());
			userRpcService.updateUser(userInfo);
		}
		SecurityAccount securityAccount = new SecurityAccount();
		securityAccount.setAccountId(userInfo.getUserId());
		securityAccount.setAccountName(userMobile);
		securityAccount.setApplicationId("180622100316646");
		response.setHeader(com.x.security.util.Constant.SECURITY_TOKEN, JWT.createJWT(securityAccount));
		redis.delete("clientLoginSmsValidCode_" + userMobile);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "登录成功", userInfo);
	}

	/**
	 * 微信登录
	 * @param user
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/loginWx", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel loginWx(User user, HttpServletResponse response, HttpServletRequest request){
		if(StringUtils.isEmpty(user.getWxOpenId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "openId不能为空！");
		}
		User userInfo = userRpcService.selectUserInfo(user);
		if (userInfo == null){
			Map<String, Object> res = new HashMap<>();
			res.put("code", 2);
			return new ResultModel(ResultCode.RESULT_SUCCESS, "该微信用户未绑定手机号", res);
		}
		SecurityAccount securityAccount = new SecurityAccount();
		securityAccount.setAccountId(userInfo.getUserId());
		securityAccount.setAccountName(user.getWxOpenId());
		securityAccount.setApplicationId("180622100316646");
		response.setHeader(com.x.security.util.Constant.SECURITY_TOKEN, JWT.createJWT(securityAccount));
		return new ResultModel(ResultCode.RESULT_SUCCESS, "登录成功", userInfo);
	}


	/**
	 * 获取登录短信验证码
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getLoginValidCode", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel getLoginValidCode(@Validated User user, BindingResult bindingResult) {
		if (bindingResult.hasErrors()){
			List<ObjectError> errors = bindingResult.getAllErrors();
			return new ResultModel(ResultCode.RESULT_FAIL, errors.get(0).getDefaultMessage());
		}
		try {
			ClientSmsCodeMsg clientSmsCodeMsg = new ClientSmsCodeMsg();
			clientSmsCodeMsg.setUserMiobile(user.getUserMobile());
			Random r = new Random();
			String validateCode = String.format("%06d", r.nextInt(1000000));
			clientSmsCodeMsg.setValidateCode(validateCode);
			redis.set("clientLoginSmsValidCode_" + user.getUserMobile(), clientSmsCodeMsg, 5 * 60);
			rocketMqProducer.produceMessage(ClientConstantTopic.TOPIC_CLIENT, ClientConstantTopic.TAG_CLIENT_LOGIN_OPR, clientSmsCodeMsg);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取短信验证码异常", e);
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "短信已发送，请查看");
	}



	/**
	 * 获取客户询价信息
	 * @param userMobile
	 * @param intentionMobile
	 * @param carId
	 * @return
	 */
	@RequestMapping(value = "/getRecordIntentionInfo", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel getRecordIntentionInfo(String userMobile, String intentionMobile, String carId){
		if (StringUtils.isEmpty(userMobile)){
			return new ResultModel(ResultCode.RESULT_FAIL, "登录用户手机号不能为空！");
		}
		if (StringUtils.isEmpty(intentionMobile)){
			return new ResultModel(ResultCode.RESULT_FAIL, "意向用户手机号不能为空！");
		}
		if (StringUtils.isEmpty(carId)){
			return new ResultModel(ResultCode.RESULT_FAIL, "意向车辆ID不能为空！");
		}
		Car carInfo = new Car();
		carInfo.setCarId(carId);
		Car car = carRpcService.selectCar(carInfo);
		if(car == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "意向车辆不存在！");
		}
		CustomerShop customerShop = new CustomerShop();
		customerShop.setShopId(car.getShopId());
		customerShop.setMarketId(car.getMarketId());
		customerShop.setChannelId(Constant.CRM_CHANNE_ID);
		customerShop.setChannelName(Constant.CRM_CHANNE_NAME);
		customerShop = insertOrUpdateCustomer(customerShop,userMobile);
		if (customerShop == null ){
			return new ResultModel(ResultCode.RESULT_FAIL, "获取记录失败！");
		}
		insertClientIntention(car,customerShop,intentionMobile);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "提交成功！");
	}


	/**
	 * 新增或者更新CRM系统客户
	 * @param customerShop
	 * @param userMobile
	 * @return
	 */
	private CustomerShop  insertOrUpdateCustomer(CustomerShop customerShop, String userMobile){
		Customer customer = new Customer();
		customer.setCustomerPhone(userMobile);
		customer.setCreateTime(this.getDate(0));
		customer.setUpdateTime(this.getDate(0));
		List<Customer> customers = customerRpcService.selectCustomerList(customer);
		if (customers != null && customers.size() > 0){
			customerShop.setCustomerId(customers.get(0).getCustomerId());
			List<CustomerShop> customerShops = customerShopRpcService.selectCustomerShopList(customerShop);
			if (customerShops == null || customerShops.isEmpty()){
				customerShop.setCustomerId(customers.get(0).getCustomerId());
				customerShop.setFollowState(1);
				customerShop = customerShopRpcService.insertCustomerShop(customerShop);
			}else{
				customerShop = customerShops.get(0);
			}
		}else{
			customer = customerRpcService.insertCustomer(customer);
			customerShop.setCustomerId(customer.getCustomerId());
			customerShop.setFollowState(1);
			customerShop = customerShopRpcService.insertCustomerShop(customerShop);
		}
		customerShop.setCustomer(customer);
		return customerShop;
	}

	/**
	 * 新增客户意向
	 * @param car
	 * @param customerShop
	 * @param intentionMobile
	 */

	private void insertClientIntention(Car car, CustomerShop customerShop, String intentionMobile) {
		Intention intention = new Intention();
		List<IntentionModel> intentionModelInfo = new ArrayList<>();
		IntentionModel intentionModel = new IntentionModel();
		intentionModel.setCarId(car.getCarId());
		intention.setCustomerShopId(customerShop.getCustomerShopId());
		intention.setCustomerMobile(intentionMobile);
		intentionModel.setIntention(intention);
		List<IntentionModel>  intentionModelList = intentionModelRpcService.selectIntentionCustomerList(intentionModel);
		if (intentionModelList.size() == 0){
			if(customerShop!=null){
				if (customerShop.getFollowState() == 2 && customerShop.getFollowerId() !=null){
					intention.setFollowerId(customerShop.getFollowerId());
					intention.setFollowerName(customerShop.getFollowerName());
					intention.setIntentionState(com.x.crm.util.Constant.INTENTION_DGJ);
					intention.setOpportunityState(com.x.crm.util.Constant.OPPORTUNITY_YCL);
				}else{
					intention.setIntentionState(com.x.crm.util.Constant.INTENTION_DFP);
					intention.setOpportunityState(com.x.crm.util.Constant.OPPORTUNITY_DCL);
				}
			}else{
				return;
			}
			intention.setIntentionState(1);
			intention.setCustomerContactName("车商城询价客户");
			intention.setIntentionType(1);//购买
			intention.setShopId(car.getShopId());
			intention.setMarketId(car.getMarketId());
			intention.setIntentionChannelId(Constant.CRM_CHANNE_ID);
			intention.setIntentionChannelName(Constant.CRM_CHANNE_NAME);
			intention.setIsOpportunity(1);
			intention.setGetTime(this.getDate(0));
			intention.setCreateTime(this.getDate(0));
			intention.setUpdateTime(this.getDate(0));
			intentionModel.setSeriesName(car.getSeries().getSeriesName());
			intentionModel.setSeriesId(car.getSeriesId().toString());
			intentionModel.setBrandName(car.getBrand().getBrandName());
			intentionModel.setBrandId(car.getBrandId().toString());
			intentionModel.setCarTitle(car.getCarTitle());
			intentionModel.setCreateTime(new Timestamp(System.currentTimeMillis()));
			intentionModel.setCarState(1);
			intentionModel.setCarImageUrl(car.getCarImageUrl());
			intentionModel.setCarRetailPrice(car.getCarRetailPrice());
			intentionModelInfo.add(intentionModel);
			intention.setIntentionModelList(intentionModelInfo);
			intentionRpcService.insertWxIntentionInfo(intention, null);
		}
	}

}
